const uniCaptcha = require('uni-captcha');
const { Joi } = require('dx-router-admin');
module.exports = {
	async login() {
		let { $dx } = this;
		let schema = Joi.object({
			username: Joi.string()
				.required()
				.error(new Error($dx.$t('the username verification fails'))),
			password: Joi.string()
				.required()
				.error(new Error($dx.$t('the password verification failed'))),
		});
		let data = $dx.request.post();
		const { error } = schema.validate(data, {
			abortEarly: true,
			allowUnknown: true,
		});
		if (error) {
			$dx.error(error.message);
		}
		const dCloudAppid = $dx.request.appId;
		const captchaAppIds = $dx.getConfig('captcha');
		let { username, password, captcha } = data;
		// 验证码校验
		if (captchaAppIds.includes(dCloudAppid)) {
			if (!captcha) {
				$dx.error($dx.$t('the verification code fails'));
			}
			let deviceId = $dx.request.deviceId;
			const verifyRes = await uniCaptcha.verify({
				captcha,
				scene: 'login',
				device_uuid: deviceId,
			});
			// 验证失败
			if (verifyRes.code !== 0) {
				$dx.error(verifyRes.errMsg);
			}
		}
		// 登陆
		const row = await $dx.service.user.where('username', username).find();
		// 用户
		if (!row) {
			// 管理员账号不存在
			if (username === 'admin') {
				return await $dx.service.user.createManageAccount();
			}
			await $dx.service.logs.addLoginLog('', username, 'login', 0);
			$dx.error('账号不存在');
		}
		// 判断密码
		if (!$dx.service.user.checkPassword(password, row.password, row.password_secret_version)) {
			await $dx.service.logs.addLoginLog(row._id, username, 'login', 0, row.mobile, row.email);
			// 锁定用户
			await $dx.service.user.lockUser(row._id, username);
			$dx.error('密码不正确');
		}
		// 判断是否禁用
		if (row.status !== 0) {
			await $dx.service.logs.addLoginLog(row._id, username, 'login', 0, row.mobile, row.email);
			$dx.error('账号已被禁用');
		}
		// 判断是否有应用权限
		if (row.dcloud_appid.length && !row.dcloud_appid.includes(dCloudAppid)) {
			await $dx.service.logs.addLoginLog(row._id, username, 'login', 0, row.mobile, row.email);
			$dx.error('账号没有应用权限');
		}
		return await $dx.service.user.loginByUser(row);
	},
};
